package com.steven.im.ui.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.steven.im.R;
import com.steven.im.adapter.CatgoodsAdapter;
import com.steven.im.adapter.MenuAdapter;
import com.steven.im.base.BaseFragment;
import com.steven.im.entity.BaseEntity;
import com.steven.im.entity.CategoryEntity;
import com.steven.im.entity.CatgoodsEntity;
import com.steven.im.net.MyCallback;
import com.steven.im.net.Task;
import com.steven.im.ui.activity.GoodsDetailActivity;
import com.steven.im.utils.GsonUtils;
import com.steven.im.utils.ScreenUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import retrofit2.Response;

/**
 * Created by Steven on 2019/1/4.
 * 分类
 */
public class ClassificationFragment extends BaseFragment {

    private static final String TAG = "CAT";

    @BindView(R.id.view_status_bar_place)
    View statusBarPlace;
    @BindView(R.id.title_left)
    ImageView titleLeft;
    @BindView(R.id.title_mid)
    TextView titleMid;

    //列表
    @BindView(R.id.lv_menu)
    ListView lvMenu;
    MenuAdapter menuAdapter;
    List<CategoryEntity> menuList = new ArrayList<>();
    String currentCatId = "";//当前选中的分类ID
    String categoryId = "";//首页跳转过来的分类ID（优先判断）

    //商品
    @BindView(R.id.iv_logo)
    ImageView ivLogo;
    @BindView(R.id.tv_menutitle)
    TextView tvMenutitle;
    @BindView(R.id.rv_goods)
    RecyclerView rvGoods;
    CatgoodsAdapter catgoodsAdapter;
    List<CatgoodsEntity> catgoodsList = new ArrayList<>();

    @SuppressLint("InflateParams")
    @Override
    public View setContentView(LayoutInflater inflater) {
        return inflater.inflate(R.layout.classification_fragment, null);
    }


    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        ViewGroup.LayoutParams params = statusBarPlace.getLayoutParams();
        params.height = ScreenUtil.getStatusBarHeight(getContext());
        statusBarPlace.setLayoutParams(params);
        titleLeft.setVisibility(View.GONE);
        titleMid.setText("分类");

        initView();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            if (getArguments() != null) {
                categoryId = getArguments().getString("categoryId");
                getArguments().putString("categoryId", "");
            }
            initData();
        }
    }

    /**
     * 初始化界面
     */
    private void initView() {
        //分类
        menuAdapter = new MenuAdapter(getActivity(), menuList);
        lvMenu.setAdapter(menuAdapter);
        lvMenu.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                currentCatId = menuList.get(i).getCategoryId();//当前选中位置的分类ID
                menuAdapter.setSelectColor(i);
                menuAdapter.notifyDataSetChanged();
                //更改商品信息
                getCatGoods(menuList.get(i).getCategoryId());
            }
        });
        //商品数据
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), 3);
        rvGoods.setLayoutManager(gridLayoutManager);
        catgoodsAdapter = new CatgoodsAdapter(getActivity(), catgoodsList);
        rvGoods.setAdapter(catgoodsAdapter);
        catgoodsAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                //跳转到商品详情
                if (ScreenUtil.isFastClick()) {
                    return;
                }
                startActivity(new Intent(getActivity(), GoodsDetailActivity.class)
                        .putExtra("goodId", catgoodsList.get(position).getGoodsId()).putExtra("issuedNo", catgoodsList.get(position).getIssuedNo()));
            }
        });

    }

    /**
     * 加载数据
     */
    private void initData() {
        Task.getApiService().getCatList().enqueue(new MyCallback<BaseEntity>(getActivity()) {
            @Override
            protected void onSuccess(Response<BaseEntity> response) {
                try {
                    if ("0".equals(response.body().getCode())) {
                        //列表
                        List<CategoryEntity> catList = GsonUtils.jsonToArrayList(
                                response.body().getResult().getJSONArray("categoryList").toString(),
                                CategoryEntity.class);
                        if (catList != null) {
                            menuList.clear();
                            menuList.addAll(catList);
                            menuAdapter.notifyDataSetChanged();

                            //显示商品
                            if (!menuList.isEmpty()) {
                                if (TextUtils.isEmpty(categoryId)) {//非跳转
                                    if (TextUtils.isEmpty(currentCatId)) {//如果没有选中项，默认选择第一项
                                        //更改商品信息
                                        menuAdapter.setSelectColor(0);
                                        menuAdapter.notifyDataSetChanged();
                                        getCatGoods(menuList.get(0).getCategoryId());
                                    } else {//如果有选中项，这显示选择项
                                        boolean isHas = true;
                                        for (int i = 0; i < menuList.size(); i++) {
                                            if (currentCatId.equals(menuList.get(i).getCategoryId())) {
                                                isHas = false;
                                                //更改商品信息
                                                menuAdapter.setSelectColor(i);
                                                menuAdapter.notifyDataSetChanged();
                                                getCatGoods(menuList.get(i).getCategoryId());
                                                break;
                                            }
                                        }
                                        if (isHas) {
                                            menuAdapter.setSelectColor(0);
                                            menuAdapter.notifyDataSetChanged();
                                            getCatGoods(menuList.get(0).getCategoryId());
                                        }
                                    }
                                } else {//显示指定项
                                    currentCatId = categoryId;//选定项为跳转的分类
                                    for (int i = 0; i < menuList.size(); i++) {
                                        if (menuList.get(i).getCategoryId().equals(categoryId)) {
                                            menuAdapter.setSelectColor(i);
                                            menuAdapter.notifyDataSetChanged();
                                            getCatGoods(menuList.get(i).getCategoryId());
                                            categoryId = "";
                                            break;
                                        }
                                    }
                                    if (!TextUtils.isEmpty(categoryId)) {//没找到，默认显示选中项
                                        if (TextUtils.isEmpty(currentCatId)) {//当前选中项为空，这显示第一项
                                            menuAdapter.setSelectColor(0);
                                            menuAdapter.notifyDataSetChanged();
                                            getCatGoods(menuList.get(0).getCategoryId());
                                        } else {//如果有选中项，这显示选择项
                                            boolean isHas = true;
                                            for (int i = 0; i < menuList.size(); i++) {
                                                if (currentCatId.equals(menuList.get(i).getCategoryId())) {
                                                    isHas = false;
                                                    //更改商品信息
                                                    menuAdapter.setSelectColor(i);
                                                    menuAdapter.notifyDataSetChanged();
                                                    getCatGoods(menuList.get(i).getCategoryId());
                                                    break;
                                                }
                                            }
                                            if (isHas) {
                                                menuAdapter.setSelectColor(0);
                                                menuAdapter.notifyDataSetChanged();
                                                getCatGoods(menuList.get(0).getCategoryId());
                                            }
                                        }
                                        categoryId = "";
                                    }
                                }
                            } else {//商品为空，跳转过来的分类ID置空
                                categoryId = "";
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            protected void onFailure(Throwable t) {

            }
        });
    }

    /**
     * 获取选中分类的商品
     */
    private void getCatGoods(String catId) {
        Task.getApiService().getCatGoods(catId).enqueue(new MyCallback<BaseEntity>(getActivity()) {
            @Override
            protected void onSuccess(Response<BaseEntity> response) {
                try {
                    Log.i(TAG, "goods:" + response.body().toString());
                    if ("0".equals(response.body().getCode())) {
                        List<CatgoodsEntity> goodsList = GsonUtils.jsonToArrayList(
                                response.body().getResult().getJSONArray("goodsList").toString(),
                                CatgoodsEntity.class);
                        if (goodsList != null) {
                            catgoodsList.clear();
                            catgoodsList.addAll(goodsList);
                            catgoodsAdapter.setNewData(catgoodsList);
                        }

                        //热卖商品
                        if (response.body().getResult().containsKey("hotGoods")) {//有热卖商品
                            final CatgoodsEntity hotGoods = GsonUtils.parseJSON(
                                    response.body().getResult().getJSONObject("hotGoods").toString(),
                                    CatgoodsEntity.class);
                            if (hotGoods != null) {
                                Glide.with(getActivity()).load(hotGoods.getPreviewImage())
                                        .into(ivLogo);
                                tvMenutitle.setText(hotGoods.getGoodsTitle());
                                ivLogo.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        if (ScreenUtil.isFastClick()) {
                                            return;
                                        }
                                        startActivity(new Intent(getActivity(), GoodsDetailActivity.class)
                                                .putExtra("goodId", hotGoods.getGoodsId())
                                                .putExtra("issuedNo", hotGoods.getIssuedNo()));
                                    }
                                });
                            } else {
                                ivLogo.setImageResource(R.drawable.classify_banner);
                                tvMenutitle.setText("");
                            }
                        } else {//没有
                            ivLogo.setImageResource(R.drawable.classify_banner);
                            tvMenutitle.setText("");
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            protected void onFailure(Throwable t) {
            }
        });
    }

}
